import { isReferee } from "@/func";
import { Player, world } from "@minecraft/server";
import { SAPIGameConfig } from "@sapi-game/config";
import { Game, GameComponent } from "@sapi-game/main";
import { Vector3Utils } from "@sapi-game/utils";
import { DimensionIds } from "@sapi-game/utils/vanila-data";
import { PixelParty } from "../game";
import { PixelPartyBackState } from "./backState";

export class PixelPartyStarter extends GameComponent<PixelPartyBackState> {
    private readonly leverPos = { x: 190, y: -53, z: -199 };

    override onAttach(): void {
        this.subscribe(world.afterEvents.leverAction, (t) => {
            if (
                t.isPowered &&
                t.dimension.id == DimensionIds.Overworld &&
                Vector3Utils.isEqual(t.block.location, this.leverPos)
            ) {
                this.handleStart(t.player);
            }
        });
    }

    checkPlayers() {
        const playerCnt = this.state.region.getPlayersInRegion().length;
        if (SAPIGameConfig.config.debugMode) {
            return playerCnt >= 1;
        } else {
            return playerCnt >= 2;
        }
    }

    handleStart(player: Player) {
        if (Game.manager.hasGame(PixelParty)) {
            return player.sendMessage("游戏已开始，请先结束");
        }
        if (!isReferee(player)) {
            return player.sendMessage("你不是裁判，无权开始");
        }
        if (!this.checkPlayers()) {
            return player.sendMessage("人数不足");
        }
        this.state.start();
    }
}
